<template>
  <div>
    <div id="alert1"></div>
    <div id="alert2"></div>
    <canvas id="canvas"></canvas>
  </div>
</template>

<script setup lang='ts'>
import { onMounted } from 'vue';

let alert1: HTMLDivElement
let alert2: HTMLDivElement
let canvas: HTMLCanvasElement
let keys: number[]
let key: number
let color: string


onMounted(() => {
  alert1 = document.querySelector('#alert1')!
  alert2 = document.querySelector('#alert2')!
  canvas = document.querySelector('#canvas')!
  keys = localstorageKeys()
  console.log(keys)
  key = keys.length == 0 ? 1 : keys[keys.length - 1] + 1
  color = ['red', 'blue', 'green'][key % 3]
  window.addEventListener('beforeunload', () => {
    localStorage.removeItem(key + '')
  })
  window.requestAnimationFrame(draw)

})



const draw = () => {
  const { clientHeight, clientWidth } = document.body
  const { screenTop, screenLeft } = window
  const tarbarHeight = window.outerHeight - window.innerHeight
  //显示实时数据
  alert1.textContent = JSON.stringify({ key, clientHeight, clientWidth, screenTop, screenLeft, tarbarHeight }, null, 2)
  //设置画布
  canvas.width = clientWidth
  canvas.height = clientHeight
  const ctx = canvas.getContext('2d')
  //设置圆点
  const x = clientWidth / 2
  const y = clientHeight / 2
  //绘制
  ctx?.beginPath()
  ctx!.fillStyle = color
  ctx?.arc(x, y, 15, 0, 2 * Math.PI)
  ctx?.fill()
  //显示当前坐标
  const position = {
    left: x + screenLeft,
    top: y + tarbarHeight + screenTop,
    color
  }
  localStorage.setItem(key + '', JSON.stringify(position, null, 2))
  alert2.textContent = JSON.stringify(localStorage, null, 2)

  localstorageKeys().forEach((item: number) => {
    let position2 = JSON.parse(localStorage.getItem(item + "")!)
    const w = position2.left - position.left
    const h = position2.top - position.top

    ctx!.strokeStyle = 'black'
    ctx?.beginPath()
    ctx?.moveTo(x, y)
    ctx?.lineTo(x + w, y + h)
    ctx?.stroke()


    ctx?.beginPath()
    ctx!.fillStyle =position2.color
    ctx?.arc(x + w, y + h, 15, 0, 2 * Math.PI)
    ctx?.fill()
  })



  window.requestAnimationFrame(draw)
}

const localstorageKeys: () => number[] = () => {
  let keys: number[] = []
  for (var i = 0; i < localStorage.length; i++) {
    const k = Number(localStorage.key(i))
    !isNaN(k) && keys.push(k)
  }
  keys = keys.sort((a, b) => {
    return a - b
  })
  return keys
}


</script>

<style scoped lang='scss'>
#alert1 {
  white-space: pre-wrap;
}

#alert2 {
  white-space: pre-wrap;
}

#canvas {
  position: absolute;
  top: 0;
  left: 0;
}
</style>